package com.customization.unionpay.market.job;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.dao.FinancialMattersDao;
import com.customization.unionpay.market.dao.MarketActivityEventDao;
import com.customization.unionpay.market.service.CheckReimbursementWorkflowService;
import com.customization.unionpay.market.service.MarketingDailyService;
import com.customization.unionpay.market.service.impl.CheckReimbursementWorkflowServiceImpl;
import com.customization.unionpay.market.service.impl.MarkertingDailyServiceImpl;
import com.customization.unionpay.market.util.FormDataUtil;
import com.customization.unionpay.market.util.FormUtil;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class financialMattersOverJob extends BaseCronJob {

    private static final Logger log = LoggerFactory.getLogger(financialMattersOverJob.class);

    @Override
    public void execute() {

        com.customization.unionpay.market.dao.MarketActivityEventDao marketActivityEventDao = new com.customization.unionpay.market.dao.MarketActivityEventDao();
        List<JSONObject> marketActivityEventList = marketActivityEventDao.queryAll();
//        List<JSONObject> originalMarketActivityEventList = marketActivityEventList;
        //如果查询出来的数据不存在 营销活动事项都不存在 不通过
        try {
            if (CollectionUtil.isEmpty(marketActivityEventList)) {
                log.error("校验不通过:营销活动事项不存在");
            } else {
                List<JSONObject> noPass = marketActivityEventList.stream()
                        .filter(o -> o.getFloatValue("yrzje") != o.getFloatValue("yhxje"))
                        .collect(Collectors.toList());

                if (CollectionUtil.isNotEmpty(noPass)) {
                    log.error("校验不通过:已入账金额与已核销金额不一致");
                    return;
                }

                // 假设这是获取下拉框枚举值的方法
                List<JSONObject> hdsfhxItem = com.customization.unionpay.market.util.FormDataUtil.getSelectItem(com.customization.unionpay.market.util.FormUtil.UF_YXHDSXTZ_ID, "hdsfhx", null);

                Integer hdsfhxYesId = hdsfhxItem.stream()
                        .filter(o -> "是".equals(o.getString("name")))
                        .map(o -> o.getInteger("value"))
                        .findFirst()
                        .orElse(null);

                List<JSONObject> filteredList = marketActivityEventList.stream()
                        .filter(o -> hdsfhxYesId.equals(o.getInteger("hdsfhx")))
                        .collect(Collectors.toList());

                //查询营销日报表台账 流水类型为异常数据状态为未确认、已确认未入账、异常数据、已结项数据、入账中和入账失败
                MarketingDailyService marketDailyService = new MarkertingDailyServiceImpl();
                //获取所有的授权码
                List<String> sqms = filteredList.stream().
                        map(o -> o.getString("yxpthdsqm")).collect(Collectors.toList());
                //查询授权码的营销日报
                List<JSONObject> marketDailyList = marketDailyService.queryBySqm(sqms);
                //查询营销日报表的状态枚举
                List<JSONObject> marketDailyZtItem = com.customization.unionpay.market.util.FormDataUtil.getSelectItem(com.customization.unionpay.market.util.FormUtil.UF_YXRBBTZ_ID, "zt", null);
                //查询营销日报表的日报流水枚举
                List<JSONObject> markerDailyRblslxItem = com.customization.unionpay.market.util.FormDataUtil.getSelectItem(com.customization.unionpay.market.util.FormUtil.UF_YXRBBTZ_ID, "rblslx", null);
                //要校验的状态枚举id 未确认、已确认未入账、入账中和入账失败
                List<Integer> marketDailyZtItemId = marketDailyZtItem.stream().filter(o -> {
                            String name = o.getString("name");
                            String[] noPassName = new String[]{"未确认", "已确认未入账", "入账中", "入账失败"};
                            return Arrays.asList(noPassName).contains(name);
                        }
                ).map(o -> o.getInteger("value")).collect(Collectors.toList());
                //要校验的状态枚举id 异常数据
                List<Integer> markerDailyRblslxItemId = markerDailyRblslxItem.stream().filter(o -> {
                            String name = o.getString("name");
                            String[] noPassName = new String[]{"异常数据"};
                            return Arrays.asList(noPassName).contains(name);
                        }
                ).map(o -> o.getInteger("value")).collect(Collectors.toList());
//                没通过的营销日报表
                List<JSONObject> noPassMarketDailyList = marketDailyList.stream().
                        filter(o -> {
                            Integer zt = o.getInteger("zt");
                            Integer rblslx = o.getInteger("rblslx");
                            return marketDailyZtItemId.contains(zt) || markerDailyRblslxItemId.contains(rblslx);
                        }).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(noPassMarketDailyList)) {
                    log.error("校验不通过:营销日报表台账状态不符合");
                    return;
                }

//                marketActivityEventList = marketActivityEventList.stream()
//                        .filter(o -> {
//                            String sqm = o.getString("yxpthdsqm");
//                            JSONObject dailyReport = marketDailyList.stream()
//                                    .filter(d -> d.getString("sqm").equals(sqm))
//                                    .findFirst()
//                                    .orElse(null);
//                            return dailyReport != null &&
//                                    !marketDailyZtItemId.contains(dailyReport.getInteger("zt")) &&
//                                    !markerDailyRblslxItemId.contains(dailyReport.getInteger("rblslx"));
//                        })
//                        .collect(Collectors.toList());
//            boolean sqmCheck = true;
//                String ysfResult = CloudFlashPaymentUtils.batchQueryByBudgetAuthCode(sqms);
//                log.info("云闪付授权码核销状态结果:" + ysfResult);
//
//                JSONObject ysfResultJson = JSONObject.parseObject(ysfResult);
//                if ("200".equals(ysfResultJson.getString("stateCode"))) {
//                    JSONArray ysfData = ysfResultJson.getJSONArray("data");
//                    log.info("云闪付数据" + ysfData);
//                    for (int i = 0; i < ysfData.size(); i++) {
//                        JSONObject ysfInfo = ysfData.getJSONObject(i);
//                        if (!"核销校验通过".equals(ysfInfo.getString("stat"))) {
//                            log.error("校验不通过:该授权码未核销");
//                            return;
//                        }
//                    }
//                }
                //查询核销报账单发票类型和是否缴纳个税，如果发票类型为活动交易流水和完税凭证或者是否缴纳个税为是
                CheckReimbursementWorkflowService checkReimbursementWorkflowService = new CheckReimbursementWorkflowServiceImpl();
                List<JSONObject> checkReimbursement = checkReimbursementWorkflowService.getCheckReimbursementWorkflowBySqm(sqms);
                if (CollectionUtil.isEmpty(checkReimbursement)) {
                    log.error("校验不通过:未查询到核销报账单信息");
                }
                //查询核销报账单的发票类型枚举
                List<JSONObject> checkReimbursementFplxItem = com.customization.unionpay.market.util.FormDataUtil.getSelectItem(com.customization.unionpay.market.util.FormUtil.CHECK_REIMBURSEMENT_ID, "fplx", null);
                //查询核销报账单的是否缴纳个税枚举
                List<JSONObject> checkReimbursementSfjngsItem = FormDataUtil.getSelectItem(FormUtil.CHECK_REIMBURSEMENT_ID, "sfjngs", null);
                //发票类型为"活动交易流水","完税凭证"ID集合
                List<Integer> filterFplxItemId = checkReimbursementFplxItem.stream().filter(o -> {
                    List<String> fplxFilter = Arrays.asList(new String[]{"活动交易流水", "完税凭证"});
                    return fplxFilter.contains(o.getString("name"));
                }).map(o -> o.getInteger("value")).collect(Collectors.toList());
                //是否缴纳个税为是的ID集合
                List<Integer> filterSfjngsItemId = checkReimbursementSfjngsItem.stream().filter(o -> {
                    List<String> sfjngsFilter = Arrays.asList(new String[]{"是"});
                    return sfjngsFilter.contains(o.getString("name"));
                }).map(o -> o.getInteger("value")).collect(Collectors.toList());
//                MarketPersonalTaxWorkflowService marketPersonalTaxWorkflowService = new MarketPersonalTaxWorkflowServiceImpl();
                //获取营销个税计提单的列表
//                List<JSONObject> marketPersonalTaxList = marketPersonalTaxWorkflowService.queryMarketPersonalTaxWorkflowBySqm(sqms);
                //营销个税计提单根据核销码分组
//                Map<String, List<JSONObject>> marketPersonalTaxMap = marketPersonalTaxList.stream()
//                        .collect(Collectors.groupingBy(o -> o.getString("yxpthdsqm")));
//                ResourceComInfo  resourceComInfo = new ResourceComInfo();
//                User user = new User();
//                user.setUid(Integer.parseInt(String.valueOf(UUID.randomUUID())));
//                user.setUserSubCompany1(Integer.parseInt(resourceComInfo.getSubCompanyID()));
//                user.setUserDepartment(Integer.parseInt(resourceComInfo.getDepartmentID()));
//                for (JSONObject o : checkReimbursement) {
//                    if (filterFplxItemId.contains(o.getInteger("fplx")) || filterSfjngsItemId.contains(o.getInteger("sfjngs"))) {
//                        List<JSONObject> list = marketPersonalTaxMap.get(o.getString("yxpthdm"));
//                        if (CollectionUtil.isEmpty(list)) {
//                            marketPersonalTaxWorkflowService.createMarketPersonalTaxWorkflow(user, o);
//                            log.error("核验不通过:未发起营销个税提计单！已自动发起营销个税提计单");
//                            return;
//                        } else {
//                            for (JSONObject jsonObject : list) {
//                                if (!jsonObject.getString("currentnodetype").equals("3")) {
//                                    log.error("核验不通过:对应营销个税提计单未归档");
//                                    return;
//                                }
//                            }
//                        }
//                    }
//                }
                FinancialMattersDao financialMattersDao = new FinancialMattersDao();
                boolean res = financialMattersDao.insert(filteredList);
                if (res) {
                    MarketActivityEventDao.updateSftstx(filteredList);
                }
                log.info("所有校验通过，数据成功插入数据库！");
            }
        } catch (Exception e) {
            log.error("执行定时任务时发生异常: {}");
        }
    }

}

